<template>
	<gui-page ref="guiPage" :customHeader="true">
		<!-- 导航 -->
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" :title="$t('barcodeChange.barcodeChange')" scanType="0"
				@clickLeftBack="clickLeftBack"></nav-bar-custom>
		</template>

		<template v-slot:gBody>
			<view class="barcodeSplitting" :style="'height: calc(100vh - ' + navHeight + 'px);'">
				<!-- 扫描和库位选择模块 -->
				<view class="gui-bg-white gui-dark-bg-level-3 gui-padding-x distributed-head">
					<view class="custom-card-title">
						<text class="title-line"></text>
						{{ $t('distributedEnter.barcodeScan') }}
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title" style="padding-right: 40rpx;"><text
								class="required-color">*</text>{{
									$t('distributedEnter.barcodeScan') }}</text>
						<uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.barcode" type="search"
							@confirm="confirm" @iconClick="iconClick" :placeholder="$t('stockManage.pleaseScanCode')">
						</uni-easyinput>
					</view>
				</view>
				<!-- 提示信息 -->
				<view class="gui-flex gui-rows gui-nowrap gui-align-items-center gui-margin-top">
					<view class="gui-title-line"></view>
					<text class="gui-primary-text gui-h6" style="padding-left:50rpx; padding-right:50rpx;">{{
						$t('hardwareOut.barcodeInformation') }}</text>
					<view class="gui-title-line"></view>
				</view>
				<scroll-view :show-scrollbar="false" :scroll-y="true" class="scroll">
					<view class="custom-form-card" v-if="Object.keys(data.scanInfo).length">
						<uni-collapse v-model="data.value">
							<uni-collapse-item titleBorder="none" :show-animation="true">
								<template v-slot:title>
									<view class="custom-card-title">
										<text class="title-line"></text>
										{{ $t('distributedOut.atPresent') }}
									</view>
								</template>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('Common.barCode') }}：</text>{{
										data.scanInfo.barcode }}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialCode') }}：</text>{{
										data.scanInfo.materialCode }}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialName') }}：</text>{{
										data.scanInfo.materialName }}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialSpec') }}：</text>{{
										data.scanInfo.materialSpec }}
								</view>
								<view class="custom-card-itemOne">
									<view class="card-item-50">
										<text class="item-info-title">{{ $t('distributedEnter.uom') }}：</text>{{
											data.scanInfo.unit }}
									</view>
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('pageTranslation.currentNumbers') }}：</text>{{
										data.scanInfo.currentQty }}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('taskList.changeQty') }}：</text>{{
										data.scanInfo.pickingQty }}
								</view>
							</uni-collapse-item>
						</uni-collapse>
					</view>
				</scroll-view>
				// <!-- 底部确定按钮 -->
				<view class="page-bottom-box bottom-postion">
					<view class="page-bottomBtn bottomBtn-bgcolor-green" @click="submit">{{ $t('calendar.submit') }}
					</view>
				</view>

				// <!-- 普通弹窗 -->
				<uni-popup ref="popup" type="center">
					<view class="input-dialog-box">
						<view class="input-dialog-content">
							<view class="input-dialog-item" >
								{{ $t('distributedEnter.materialCode') }}:{{ data.scanInfo.materialCode }}
							</view>
							<view class="input-dialog-item" style="padding:20rpx 0">
								{{ $t('pageTranslation.currentNumbers') }}:{{ data.scanInfo.currentQty }}
							</view>
							<view class="input-dialog-item flexclass" style="padding:20rpx 0">
								<view>{{ $t('taskList.changeQty') }}：</view>
								<view class="input-dialog-item-count">
									<uni-easyinput v-model="data.scanInfo.pickingQty" type="number" />
								</view>
							</view>
						</view>
						<view class="input-dialog-footer">
							<!-- <view class="input-dialog-button" @click="cancelFn">
								{{ $t('popup.cancel') }}
							</view> -->
							<view class="input-dialog-button dialog-button-left" @click="scanConfirmFn">
								{{ $t('popup.confirm') }}
							</view>
						</view>
					</view>
				</uni-popup>
			</view>
		</template>
	</gui-page>
</template>

<script setup>
//引入文件
import { navigateBack } from '@/utils/routerSkip.js';
import { ref, reactive, onMounted, computed } from "vue";
import { changeBarcodeSubmit, wmsSelectWmsBarcodeInfo } from '@/api/api.js'
import pdaScan from '@/hooks/pdaScan.js'
import { onBackPress } from '@dcloudio/uni-app';
import { useStore } from "vuex";
import { basPdaOperationLogFn } from '@/utils/index.js';
import { USERINFO, OPERATION_COMMIT, OPERATION_LOOK, OPERATION_SCAN } from '@/constant/index.js'

//JS国际化引入
import { useI18n } from 'vue-i18n';
const { t } = useI18n();
let store = useStore();

const { scan } = pdaScan()

const navHeight = computed(() => {
	return store.state.navHeight
})
// 弹框的属性
let popup = ref(null);

const data = reactive({
	barcode: '',
	scanInfo: {},// 当前扫码
	barcodeList: [],// 扫描记录的存储
	pickingQty: 0,//领料数量
	value: ['0'],
})

//定时弹框输入数量
onMounted(() => {
	uni.$on('scancodedate', (data) => {
		console.log('获取到的code：' + + data.code)
		getCode(data.code, 'pda')
	})
})

// 存储扫描数据到vuex
data.barcodeList = computed(() => {
	return store.state.barcodeChangeList
})

// 扫描条码事件
const confirm = () => {
	getCode(data.barcode, 'keydown')
}

// 监听用户使用相机
const iconClick = async (type) => {
	if (type === 'suffix') {
		let code = await scan();
		getCode(code, 'scan')
	}
}

const getCode = (code, type) => {
	if (code.length <= 0) {
		uni.showToast({ title: t('newTranslation.correctly'), icon: 'none' });
		return
	}
	// 存储扫描的的条码,通过barode去判断是否有重复
	let arr = data.barcodeList.filter(x => x.barcode == code);

	if (arr.length > 0) {
		uni.showToast({ title: t('smashRemoval.codesRepeatedly'), icon: 'none' });
		return
	}

	data.barcode = code;
	wmsSelectWmsBarcodeInfo({
		barcode: data.barcode,
		selectType: "barcodeChange"
	}).then(res => {
		try {
			let inputParameter = JSON.stringify({
				barcode: data.barcode,
				selectType: "barcodeChange"
			})
			let returnParameter = JSON.stringify(res)
			let operationPicture = '条码变更'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status,//返回状态
				errorMessage: res.message,//错误信息
				isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_SCAN
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.status == 200) {
			// 扫描条码时，判断条码数量是否大于0，如<=0,提示"条码数量为0，不允许变更! ";
			if (res.data.currentQty <= 0) {
				uni.showToast({ title: t('barcodeChange.barcodeNumber'), icon: "none" });
				data.barcode = ''
				return
			}
			// 打开弹框
			popup.value.open();
			data.scanInfo = res.data
			data.scanInfo.pickingQty = 0
			data.scanInfo.attribute1 = 0
		}
		else {
			// 扫描条码时，判断条码是否在库，如不在库提示"条码不在库，不允许变更!
			uni.showToast({ title: t('barcodeChange.barCodeIsNot') + res.message, icon: "none" });
		}
	})

}

// 弹框的确定
const scanConfirmFn = () => {
	// 判断条码数量是否为负数，
	if (Number(data.scanInfo.currentQty) < 0) {
		uni.showToast({ title: t('barcodeChange.lessThan'), icon: "none" });
		return
	}
	// 领料数量小于等于条码数量
	if (Number(data.scanInfo.pickingQty) > Number(data.scanInfo.currentQty)) {
		uni.showToast({ title: t('barcodeChange.materialQtyOnly'), icon: "none" });
		return
	}
	if (Number(data.scanInfo.pickingQty) <= 0) {
		uni.showToast({ title: t('barcodeChange.materialQtyZ'), icon: "none" });
		return
	}
	try {
			let inputParameter = JSON.stringify(data.scanInfo)
			let returnParameter = '无'
			let operationPicture = '条码变更'
			let callInterface = '无'
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode:'无',//返回状态
				errorMessage:'无',//错误信息
				isPass:'Y',//是否成功 Y N
				operationType:OPERATION_LOOK
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
	store.commit('addBarcodeChangeList', data.scanInfo)
	popup.value.close();
}

// 提交
const submit = () => {
	console.log(data.barcodeList)
	if (!data.barcodeList.length) {  //判断请扫描条码
		uni.showToast({
			title: t('stockManage.pleaseScanCode'),
			icon: 'none'
		})
		return
	}
	let parmes = {
		barcode: data.barcodeList[0].barcode,
		changeQty: Number(data.barcodeList[0].pickingQty)
	}
	// 添加加载框
	uni.showLoading({
		title: 'loading',
		mask: true
	});
	changeBarcodeSubmit(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '条码变更'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status,//返回状态
				errorMessage: res.message,//错误信息
				isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_COMMIT
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.status == 200) {
			//隐藏加载框
			uni.hideLoading();
			// 清空数据
			data.barcode = ""
			data.scanInfo = {};
			store.commit('deleteBarcodeChangeList')
			uni.showToast({ title: t('smashRemoval.submitSuccessfully'), icon: "none" });
		} else {
			uni.showToast({
				title: res.message,
				icon: 'none'
			})
		}
	})

}

//点击物理按键的返回
onBackPress((options) => {
	if (options.from == 'backbutton') {
		navBackCheck()
		return true;
	}
})
//导航栏左侧返回
const clickLeftBack = () => {
	navBackCheck()
}

const navBackCheck = () => {
	if (!data.barcodeList.length) {
		uni.navigateBack({
			delta: 1
		});
		return true
	}
	uni.showModal({
		title: t('smashRemoval.warmPrompt'),
		content: t('materials.unsubmittedDataIn'),
		success: function (res) {
			if (res.confirm) {
				//清除store 里面的数据
				store.commit("clearBarcodeChangeList");
				uni.navigateBack({
					delta: 1
				});
			} else if (res.cancel) {
				console.log('用户点击取消');
			}
		}
	});
	return true;

}

</script>

<style lang="scss" scoped>
.barcodeSplitting {
	display: flex;
	flex-direction: column;
	height: calc(100vh - 88rpx);
	// height: 100vh;
}

.distributed-head {
	border-bottom-left-radius: 16rpx;
	border-bottom-right-radius: 16rpx;
}

.scroll {
	flex: 1;
	height: 2rpx;
}

.page-bottom-box {
	position: absolute;
	left: 0px;
	bottom: 0px;
	width: 100%;
}
</style>>
